package edu.zjut.hjg.saas.biz.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import edu.zjut.hjg.saas.biz.dao.BabyDao;
import edu.zjut.hjg.saas.biz.model.Baby;
import edu.zjut.hjg.saas.biz.support.Paginated;

public class BabyDaoImpl extends SqlMapClientDaoSupport implements BabyDao {

    @Override
    public Integer create(Baby baby) {
        return (Integer) getSqlMapClientTemplate().insert("baby.create", baby);
    }

    @Override
    public void deleteByIdAndAppId(int id, int appId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", id);
        params.put("appId", appId);
        getSqlMapClientTemplate().delete("baby.deleteByIdAndAppId", params);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Paginated<Baby> listByAppId(int appId, int pageSize, int page) {
        Map<String, Object> params = new HashMap<String, Object>();
        Integer totalSize = (Integer) getSqlMapClientTemplate().queryForObject("baby.countByAppId",
                appId);
        int start = pageSize * (page - 1);
        if (start > totalSize) {
            start = (totalSize / pageSize) * pageSize;
        }
        params.put("appId", appId);
        params.put("pageSize", pageSize);
        params.put("start", start);
        List<Baby> list = getSqlMapClientTemplate().queryForList("baby.listByAppId", params);
        Paginated<Baby> paginated = new Paginated<Baby>();
        paginated.setValues(list);
        paginated.setPageSize(pageSize);
        paginated.setStart(start);
        paginated.setTotalSize(totalSize);
        return paginated;
    }

    @Override
    public Baby load(int id) {
        return (Baby) getSqlMapClientTemplate().queryForObject("baby.load", id);
    }

    @Override
    public void update(Baby baby) {
        getSqlMapClientTemplate().update("baby.update", baby);
    }

    @Override
    public Baby findByIdAndAppId(int id, int appId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", id);
        params.put("appId", appId);
        return (Baby) getSqlMapClientTemplate().queryForObject("baby.findByIdAndAppId", params);
    }

    @Override
    public void deleteBySchoolClassIdAndAppId(int schoolClassId, int appId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("schoolClassId", schoolClassId);
        params.put("appId", appId);
        getSqlMapClientTemplate().delete("baby.deleteBySchoolClassIdAndAppId", params);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Baby> listAllByAppId(int appId) {
        return getSqlMapClientTemplate().queryForList("baby.listAllByAppId", appId);
    }
}
